package com.danco.planner.controllers.core.singleton;

import java.util.Scanner;
import java.util.Stack;

import com.danco.planner.controllers.core.ViewController;
import com.danco.planner.supportclasses.enumeration.DefaultEventType;

public class ConsoleWindowDirector {
	
	protected static ConsoleWindowDirector sharedWindow;
	public static ConsoleWindowDirector getSharedWindow() {
		
		if (sharedWindow == null) {
			sharedWindow = new ConsoleWindowDirector();
		}
		return sharedWindow;
	}
	protected ConsoleWindowDirector() {
		super();
		stackOfVC = new Stack<ViewController>();
	}
	
	public static void runConsoleAppWithViewController(ViewController vc) {
		
		getSharedWindow().pushViewController(vc);
		getSharedWindow().lifeCycle();
	}
	
	protected Stack<ViewController> stackOfVC;
	
	public void pushViewController(ViewController vc) {
		
		if (vc == null) return;
		
		stackOfVC.push(vc);
	}
	public void popViewController(ViewController vc) {
		
		while (stackOfVC.contains(vc)) {
			stackOfVC.pop();
		}
	}
	

	// Console features
	public void lifeCycle() {
		
		do {
			show();
			
			String command = waitNextCommand();
			if (command != null) {
				stackOfVC.peek().doActionWithType(DefaultEventType.None, command);
			}
		}
		while (stackOfVC.size() > 0);
	}
	protected String waitNextCommand() {
		
		System.out.print("Enter command: ");
		
		Scanner scan = new Scanner(System.in);
		String result = scan.nextLine();
		return result;
	}

	protected void show() {
		
		// how can I clear the console window?
		System.out.println("--------------------------------------------------------------------------");
		System.out.println("-----------------------------UPDATE-SCREEN--------------------------------");
		System.out.println("--------------------------------------------------------------------------");
		
		if (stackOfVC.size() == 0) {
			System.exit(0);
		}
		
		ViewController vc = stackOfVC.peek();
		if (vc != null) {
			vc.show();
		}
		
	}
}
